package com.tanjun.userservice.web.service.user.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tanjun.common.constants.DefaultConstant;
import com.tanjun.common.exception.BizException;
import com.tanjun.userservice.web.service.user.entity.BaseAdminDeptEntity;
import com.tanjun.userservice.web.service.user.mapper.BaseAdminDeptMapper;
import com.tanjun.userservice.web.service.user.BaseAdminDeptService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 管理员部门表 服务层实现。
 *
 * @author tanjun
 * @since 2025-08-20
 */
@Service
public class BaseAdminDeptServiceImpl extends ServiceImpl<BaseAdminDeptMapper, BaseAdminDeptEntity>  implements BaseAdminDeptService {

    /**
     * 新增部门
     *
     * @param baseAdminDeptEntity
     */
    @Override
    public void addDept(BaseAdminDeptEntity baseAdminDeptEntity) {
        //1.先判断部门编码是否重复
        handlerParam(baseAdminDeptEntity);
        this.save(baseAdminDeptEntity);
    }

    /**
     * 修改部门
     *
     * @param dept
     */
    @Override
    public void updateDept(BaseAdminDeptEntity dept) {
        handlerParam(dept);
        dept.setUpdateTime(LocalDateTime.now());
        this.updateById(dept);
    }

    /**
     * 删除部门
     *
     * @param id 部门id
     */
    @Override
    public void delDept(Long id) {
        BaseAdminDeptEntity dept = this.getById(id);
        if(dept==null){
            throw new BizException("数据不存在");
        }
        long childCount=this.count(QueryChain.of(BaseAdminDeptEntity.class)
                .eq(BaseAdminDeptEntity::getParentId,dept.getId())
        );
        if(childCount>0){
            throw new BizException("存在子部门，无法删除");
        }
        //todo 判断部门是否存在用户

        this.removeById(id);
    }

    /**
     * 根据id获取部门信息
     *
     * @param ids ids
     * @return 部门列表
     */
    @Override
    public List<BaseAdminDeptEntity> listAdminDeptById(Collection<Long> ids) {
        return this.listByIds(ids);
    }

    /**
     * 获取所有的子级部门id
     *
     * @param parentId 父级部门id
     * @return 返回子级部门id
     */
    @Override
    public List<BaseAdminDeptEntity> getChildrenDept(Long parentId) {
        BaseAdminDeptEntity dept=this.getById(parentId);
        if(dept==null){
            return null;
        }
        return QueryChain.of(this.mapper)
                .likeRight(BaseAdminDeptEntity::getParentId,
                        (StrUtil.isNotEmpty(dept.getFullParentId())?dept.getFullParentId()+ DefaultConstant.SPLIT:StrUtil.EMPTY)+
                        dept.getId()+DefaultConstant.SPLIT)
                .or(BaseAdminDeptEntity::getParentId).eq(dept.getId())
                .list();
    }

    /**
     * 获取所有的子集以及自己的部门id
     *
     * @param parentId 父级部门id
     * @return 部门id list
     */
    @Override
    public List<Long> getChildrenAndSelfDeptId(Long parentId) {
        List<BaseAdminDeptEntity> listDept=getChildrenDept(parentId);
        List<Long> list=new ArrayList<>();
        if(CollUtil.isNotEmpty(listDept)){
            list.addAll(listDept.stream().map(BaseAdminDeptEntity::getId).toList());
            list.add(parentId);
        }
        return list;
    }

    /**
     * 查询所有的部门信息
     *
     * @return 查询所有的部门信息
     */
    @Override
    public List<BaseAdminDeptEntity> listAll() {
        return QueryChain.of(BaseAdminDeptEntity.class)
                .orderBy(BaseAdminDeptEntity::getLevel)
                .asc().
                orderBy(BaseAdminDeptEntity::getSort)
                .asc()
                .orderBy(BaseAdminDeptEntity::getDeleted)
                .asc()
                .list();
    }

    /**
     * 处理新增和修改的数据检查
     * @param dept
     */
    private void handlerParam(BaseAdminDeptEntity dept){
        long countCode= this.count(QueryChain.of(BaseAdminDeptEntity.class)
                .eq(BaseAdminDeptEntity::getDeptCode, dept.getDeptCode())
                .ne(BaseAdminDeptEntity::getId, dept.getId(),dept.getId()!=null)
        );
        if(countCode>0){
            throw new BizException("部门编码重复");
        }
        if(dept.getParentId()!=null&&dept.getParentId()>0){
            BaseAdminDeptEntity parentDept=this.getById(dept.getParentId());
            if(parentDept==null){
                throw new BizException("父级部门信息不存在");
            }
            String parentFullId=null;
            if(StrUtil.isNotEmpty(parentDept.getFullParentId())){
                parentFullId=parentDept.getFullParentId()+ DefaultConstant.SPLIT+parentDept.getId();
            }
            else {
                parentFullId=parentDept.getId().toString();
            }
            dept.setFullParentId(parentFullId);
            dept.setLevel(parentDept.getLevel()+1);
        }
        else {
            dept.setFullParentId(StrUtil.EMPTY);
            dept.setLevel(1);
        }
    }
}
